package chuangyi.com.org.ViewModel;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.databinding.Bindable;
import android.view.View;

import com.solidfire.gson.internal.LinkedTreeMap;
import com.umeng.socialize.ShareContent;
import com.umeng.socialize.media.UMImage;

import java.util.ArrayList;
import java.util.List;

import chuangyi.com.org.DOMIHome.BR;
import chuangyi.com.org.DOMIHome.HomeActivity;
import chuangyi.com.org.DOMIHome.LoadingDialog;
import chuangyi.com.org.DOMIHome.PopupActivity;
import chuangyi.com.org.DOMIHome.R;
import chuangyi.com.org.DOMIHome.Utils.Utils;
import chuangyi.com.org.DOMIHome.Utils.WebApi;
import chuangyi.com.org.DOMIHome.WaitActivityResult;
import chuangyi.com.org.DOMIHome.adapter.ListBindingAdapter;

/**
 * Created by zxh on 16/12/5.
 */

public class ArticleDetail extends ObservableWithGoBackHandler implements WaitActivityResult {
    private ArticleItem article;
    // 段落列表
    private ListBindingAdapter paragraphList;
    // 相关文章
    private ListBindingAdapter articles;
    // 评论列表
    private ListBindingAdapter commentList;

    private ListBindingAdapter<ClickMenuItem> menus;

    private int commentcount;
    private int collectcount;
    private int likecount;
    private int sharecount;
    private boolean collectflag;
    private boolean likeflag;
    private boolean attentionFlag;
    private String avatar;
    private String nickName;
    private String commentContent;
    //    private Date uploadtime;
    private boolean descSelected;
    private boolean commentSelected;
//    private int collectImageSource;
//    private int likeImageSource;


    @Bindable
    public ListBindingAdapter<ClickMenuItem> getMenus() {
        return menus;
    }

    @Bindable
    public boolean isDescSelected() {
        return descSelected;
    }

    public void setDescSelected(boolean descSelected) {
        if (this.descSelected != descSelected && descSelected) {
            setCommentSelected(false);
            loadRelatedArticle();
        }
        this.descSelected = descSelected;
        notifyPropertyChanged(BR.descSelected);
    }

    @Bindable
    public boolean isCommentSelected() {
        return commentSelected;
    }

    public void setCommentSelected(boolean commentSelected) {
        this.commentSelected = commentSelected;
        if (this.commentSelected) {
            setDescSelected(false);
            loadCommentList();
        }
        notifyPropertyChanged(BR.commentSelected);
    }

    @Bindable
    public ArticleItem getArticle() {
        return article;
    }

    public void setArticle(ArticleItem article) {
        this.article = article;
    }

    @Bindable
    public int getCommentcount() {
        return commentcount;
    }

    public void setCommentcount(int commentcount) {
        this.commentcount = commentcount;
    }

    @Bindable
    public ListBindingAdapter getParagraphList() {
        return paragraphList;
    }

    @Bindable
    public ListBindingAdapter getCommentList() {
        return commentList;
    }

    @Bindable
    public int getCollectcount() {
        return collectcount;
    }

    public void setCollectcount(int collectcount) {
        this.collectcount = collectcount;
        notifyPropertyChanged(BR.collectcount);
    }

    @Bindable
    public int getLikecount() {
        return likecount;
    }

    public void setLikecount(int likecount) {
        this.likecount = likecount;
        notifyPropertyChanged(BR.likecount);
    }

    @Bindable
    public int getSharecount() {
        return sharecount;
    }

    public void setSharecount(int sharecount) {
        this.sharecount = sharecount;
        notifyPropertyChanged(BR.sharecount);
    }

    @Bindable
    public boolean isCollectflag() {
        return collectflag;
    }

    public void setCollectflag(boolean collectflag) {
        this.collectflag = collectflag;
//        if (likeflag) {
//            setCollectImageSource(R.mipmap.collectact);
//        } else {
//            setCollectImageSource(R.mipmap.study_collect);
//        }
        notifyPropertyChanged(BR.collectflag);
    }

    @Bindable
    public boolean isLikeflag() {
        return likeflag;
    }

    @Bindable
    public boolean isAttentionFlag() {
        return attentionFlag;
    }

    public void setAttentionFlag(boolean attentionFlag) {
        this.attentionFlag = attentionFlag;
        notifyPropertyChanged(BR.attentionFlag);
    }

    public void setLikeflag(boolean likeflag) {
        this.likeflag = likeflag;
//        if (likeflag) {
//            setLikeImageSource(R.mipmap.likeact);
//        } else {
//            setLikeImageSource(R.mipmap.study_like);
//        }
        notifyPropertyChanged(BR.likeflag);
    }

//    @Bindable
//    public int getCollectImageSource() {
//        return collectImageSource;
//    }
//
//    public void setCollectImageSource(int collectImageSource) {
//        this.collectImageSource = collectImageSource;
//        notifyPropertyChanged(BR.collectImageSource);
//    }
//
//    @Bindable
//    public int getLikeImageSource() {
//        return likeImageSource;
//    }
//
//    public void setLikeImageSource(int likeImageSource) {
//        this.likeImageSource = likeImageSource;
//        notifyPropertyChanged(BR.likeImageSource);
//    }

    @Bindable
    public String getAvatar() {
        return avatar;
    }

    public void setAvatar(String avatar) {
        this.avatar = avatar;
    }

    @Bindable
    public String getNickName() {
        return nickName;
    }

    public void setNickName(String nickName) {
        this.nickName = nickName;
    }

    @Bindable
    public String getCommentContent() {
        return commentContent;
    }

    public void setCommentContent(String commentContent) {
        this.commentContent = commentContent;
        notifyPropertyChanged(BR.commentContent);
    }

    @Bindable
    public ListBindingAdapter getArticles() {
        return articles;
    }

    public ArticleDetail(Context context, ArticleItem articleItem) {
        super(context);
        this.article = articleItem;
        this.descSelected = true;
        super.getHandler().setTitle(article.getTitle());
        List<Integer> paragraphTypes = new ArrayList<Integer>();
        paragraphTypes.add(R.layout.i_text_paragraph);
        paragraphTypes.add(R.layout.i_image_paragraph);
        this.paragraphList = new ListBindingAdapter(getContext(), BR.paragraph, paragraphTypes);
        this.commentList = new ListBindingAdapter(getContext(), BR.comment);
        articles = new ListBindingAdapter<ArticleItem>(getContext(), BR.article);
        menus = new ListBindingAdapter<ClickMenuItem>(getContext(), BR.menu);
//        this.likeImageSource = R.mipmap.study_like;
//        this.collectImageSource = R.mipmap.study_collect;
        loadRelatedArticle();
        load();
    }

    /**
     * 点击用户头像，打开个人中心
     *
     * @param view
     */
    public void onClickAvatar(View view) {
        HomeActivity.showPersonalCentral(getContext(), article.getUid());
    }

    /**
     * 点击收藏
     *
     * @param view
     */
    public void onClickCollect(View view) {
        final Context context = getContext();
        new Thread(new Runnable() {
            @Override
            public void run() {
                int count = 0;
                if (collectflag) {
                    count = WebApi.removeCollection(context, "w", article.getArticleId());
                } else {
                    count = WebApi.addCollection(context, "w", article.getArticleId());
                }
                if (count >= 0) {
                    setCollectflag(!collectflag);
                    setCollectcount(count);
                }
            }
        }).start();
    }

    /**
     * 点击分享
     *
     * @param view
     */
    public void onClickShare(View view) {
        Activity activity = (Activity) getContext();
        ShareModel model = new ShareModel(activity);
        model.setShareType("article");
        model.setId(article.getArticleId());
        model.setShareCallback(new ShareModel.Callback() {
            @Override
            public void onShareSuccess() {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        int count = WebApi.docShare(getContext(), getArticle().getArticleId());
                        if (count >= 0) {
                            setSharecount(count);
                        }
                    }
                }).start();
            }

            @Override
            public void onShare(ShareItem shareItem) {
                ShareContent content = new ShareContent();
                content.mTitle = ShareModel.SHARE_TITLE;
                content.mText = ShareModel.SHARE_TEXT;
                content.mMedia = new UMImage(getContext(), ShareModel.SHARE_IMG);
                content.mTargetUrl = WebApi.getShareUrl();
                shareItem.setShareData(content);
            }
        });
        PopupActivity.startActivity(activity, R.layout.v_dialog_share, BR.share, model);
    }

    /**
     * 点击赞
     *
     * @param view
     */
    public void onClickLike(View view) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                int count = WebApi.docLike(getContext(), getArticle().getArticleId());
                if (count == -1) {
                    return;
                } else {
                    setLikecount(count);
                }
                setLikeflag(true);
            }
        }).start();
    }

    /**
     * 点击加关注
     *
     * @param view
     */
    public void onClickAttention(View view) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                if (!attentionFlag) {
                    if (WebApi.addAttention(getContext(), getArticle().getUid())) {
                        showToast("关注成功");
                        setAttentionFlag(true);
                    }
                } else {
                    if (WebApi.unAttention(getContext(), getArticle().getUid())) {
                        showToast("已取消关注");
                        setAttentionFlag(false);
                    }
                }
            }
        }).start();
    }

    /**
     * 点击举报
     *
     * @param view
     */
    public void onClickComplain(View view) {
        complainConfirm();
    }

    /**
     * 发表评论
     *
     * @param view
     */
    public void onSendComment(View view) {
        if (Utils.isNullOrEmpty(commentContent)) {
            showToast("评论内容不能为空");
            return;
        }
        LoadingDialog.getInstance(getContext()).show();
        new Thread(new Runnable() {
            @Override
            public void run() {
                if(!WebApi.allowAction(getContext())){
                    LoadingDialog.getInstance(getContext()).dismiss();
                    return;
                }
                if (WebApi.sendComment(getContext(), getArticle().getArticleId(), "w", getCommentContent())) {
                    setCommentContent("");
                    LoadingDialog.getInstance(getContext()).dismiss();
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            loadCommentList();
                        }
                    });
                }
                LoadingDialog.getInstance(getContext()).dismiss();
            }
        }).start();
    }

    /**
     * 加载数据
     */
    public void load() {
        final Context context = super.getContext();

        commentList.clear(true);
        paragraphList.clear(true);
        new Thread(new Runnable() {
            @Override
            public void run() {

                List menuList = WebApi.getMenus(context);
                for (Object menu : menuList) {
                    LinkedTreeMap map = (LinkedTreeMap) menu;
                    ClickMenuItem item = new ClickMenuItem(context, R.layout.i_click_menu);
                    item.setCode((String) map.get("code"));
                    item.setTitle((String) map.get("title"));
                    menus.add(item);
                }
                notifyDataSetChanged(menus);

                List commentItems = WebApi.getCommentList(context, "w", article.getArticleId());
                try {
                    for (Object comment : commentItems) {
                        LinkedTreeMap map = (LinkedTreeMap) comment;
                        CommentItem item = new CommentItem(context, R.layout.i_comment);
                        item.setCommentType("w");
                        item.setUid(Integer.valueOf((String) map.get("uid")));
                        item.setCommenttime(Utils.getDateFromFormat(map.get("commenttime"), "yyyy-MM-dd HH:mm:ss"));
                        item.setCommentid(Utils.getIntValue(map.get("commentid")));
                        item.setCommentlike(Utils.getIntValue(map.get("commentlike")));
                        item.setCommentcontent((String) map.get("commentcontent"));
                        item.setAvatar((String) map.get("avatar"));
                        item.setReply(Utils.getIntValue(map.get("reply")));
                        item.setJob((String) map.get("job"));
                        item.setIndustry((String) map.get("industry"));
                        commentList.add(item);
                    }
                } catch (Exception ex) {
                    showToast("解析数据时发生错误");
                }

                LinkedTreeMap map = WebApi.getDocumentDetail(context, article.getArticleId());
//                文章id：articleid，标题：title、正文：list、作者昵称:nickname、头像:avatar、
// 文章日期:systime、作者关注:attentionflag、是否点赞：likeflag、是否收藏：collectflag、
// 点赞数：doclike、收藏数：collect、分享数：docshare

                if (map != null) {
                    article.setTitle((String) map.get("title"));
                    article.setAuthor((String) map.get("nickname"));
                    article.setAvatar((String) map.get("avatar"));
                    article.setUploadtime(Utils.getDateFromFormat(map.get("systime"), "yyyy-MM-dd HH:mm:ss"));
                    article.setUid(Utils.getIntValue(map.get("uid")));

                    setLikeflag(Utils.getBooleanValue(map.get("likeflag")));
                    setCollectflag(Utils.getBooleanValue(map.get("collectflag")));
                    setAttentionFlag(Utils.getBooleanValue(map.get("attentionflag")));
                    setLikecount(Utils.getIntValue(map.get("doclike")));
                    setCollectcount(Utils.getIntValue(map.get("collect")));
                    setSharecount(Utils.getIntValue(map.get("docshare")));
//                    map = WebApi.getParagraphList(context, article.getArticleId());
                    ArrayList list = (ArrayList) map.get("infolist");
                    try {
                        if (list != null) {
                            for (Object item : list) {
                                LinkedTreeMap inner = (LinkedTreeMap) item;
                                int contentType = Utils.getIntValue(inner.get("contenttype"));
                                ParagraphItem paragraph = new ParagraphItem(getContext(), contentType);
                                paragraph.setContent((String) inner.get("content"));
                                paragraph.setAllowEdit(false);
                                paragraphList.add(paragraph);
                            }
                        }
                    } catch (Exception ex) {
                        showToast("解析数据时发生错误");
                    }
                }
                notifyDataSetChanged(commentList);
                notifyDataSetChanged(paragraphList);
            }
        }).start();
    }

    private void loadRelatedArticle() {
//        文章id：articleid，标题：title、作者昵称:nickname、头像:avatar、文章日期:systime
        articles.clear(true);
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    ArrayList result = WebApi.getRelatedArticle(getContext(), getArticle().getArticleId());
                    for (Object article : result) {
                        LinkedTreeMap map = (LinkedTreeMap) article;
                        ArticleItem item = new ArticleItem(getContext(), R.layout.i_article_simple);
                        item.setUid(Utils.getIntValue(map.get("uid")));
                        item.setAuthor((String) map.get("nickname"));
                        item.setAvatar((String) map.get("avatar"));
                        item.setTitle((String) map.get("title"));
                        item.setContent((String) map.get("content"));
                        item.setArticleId(Utils.getIntValue(map.get("articleid")));
                        item.setUploadtime(Utils.getDateFromFormat(map.get("systime"), "yyyy-MM-dd HH:mm:ss"));
                        articles.add(item);
                    }
                    notifyDataSetChanged(articles);
                } catch (Exception ex) {
                    showToast("解析数据时发生错误");
                }
            }
        }).start();
    }

    private void loadCommentList() {
        final Context context = super.getContext();
        commentList.clear(true);
        new Thread(new Runnable() {
            @Override
            public void run() {
                List commentItems = WebApi.getCommentList(context, "w", getArticle().getArticleId());
                try {
                    for (Object comment : commentItems) {
                        LinkedTreeMap map = (LinkedTreeMap) comment;
                        CommentItem item = new CommentItem(context, R.layout.i_comment);
                        item.setCommentType("w");
                        item.setUid(Integer.valueOf((String) map.get("uid")));
                        item.setName((String) map.get("nickname"));
                        item.setCommenttime(Utils.getDateFromFormat(map.get("commenttime"), "yyyy-MM-dd HH:mm:ss"));
                        item.setCommentid(Utils.getIntValue(map.get("commentid")));
                        item.setCommentlike(Utils.getIntValue(map.get("commentlike")));
                        item.setCommentcontent((String) map.get("commentcontent"));
                        item.setAvatar((String) map.get("avatar"));
                        item.setReply(Utils.getIntValue(map.get("reply")));
                        item.setJob((String) map.get("job"));
                        item.setIndustry((String) map.get("industry"));
                        commentList.add(item);
                    }
                    notifyDataSetChanged(commentList);
                } catch (Exception ex) {
                    showToast("解析数据时发生错误");
                }
                notifyDataSetChanged(commentList);
            }
        }).start();
    }

    public void complainConfirm() {
        new AlertDialog.Builder(getContext()).setTitle("确认").setMessage("确定提交投诉吗？")
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                if (WebApi.sendComplain(getContext(), article.getArticleId(), "w")) {
                                    showToast("您的投诉已提交，我们会尽快核实并处理，谢谢");
                                }
                            }
                        }).start();
                    }
                })
                .setNegativeButton("返回", null).show();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == HomeActivity.REQUEST_SHARE) {

            }
        }
    }
}
